import axios from 'axios'
import router from '../router/index'
import {useLoading} from 'vue-loading-overlay'
import {toast} from "vue3-toastify";
const $loading = useLoading({});

const http = axios.create({
    // baseURL: "http://localhost:8090",
    timeout: 10000,
    responseType: 'json'
})

let loading = null;

http.interceptors.request.use(config => {
    loading = $loading.show();
    config.headers['Authorization'] = `Bearer ${sessionStorage.getItem('token')}`
    return config
})

http.interceptors.response.use(res => {
    loading.hide();
    if (res.status === 200) {
        if (res.data.code === 401) {
            toast(res.data.msg, {autoClose: 2000, type: 'error', onClose: () => router.replace('/login')});
        } else if (res.data.code === 402) toast('你当前没有权限访问该模块！', {autoClose: 2000, type: 'error'});
        else if (res.data.code === 500) toast('服务器错误，请联系管理员', {autoClose: 2000, type: 'error'});
        else if (res.data.code === 400) toast(res.data.msg, {autoClose: 2000, type: 'error'});
        return res.data
    } else toast('服务器错误，请联系管理员', {autoClose: 2000, type: 'error'});
}, err => {
    loading.hide();
    if (err.message.indexOf('401') > -1) {
        return toast('页面未找到', {autoClose: 2000, type: 'error', onClose: () => router.replace('/')});
    }
    console.log(err);
    toast(err, {autoClose: 2000, type: 'error'});
})

export default http
